//
//  WXPLoginAuthVC.m
//  MexicoLoan
//
//  Created by wxp on 2025/2/27.
//

#import "WXPLoginAuthVC.h"
#import "WXPFaceScanBtn.h"
#import "WXPFaceErrorExampleView.h"
#import "WXPFaceCameraVC.h"
#import "WXPWebLivenessVC.h"
#import "WXPLivenessFailView.h"
#import "ServiceVC.h"



@interface WXPLoginAuthVC ()

@property (nonatomic, strong) WXPNavView * navView;
@property (nonatomic, strong) UIView * headerView;


@property (nonatomic, strong) WXPTextRemindView * remindView;
@property (nonatomic, strong) WXPFaceScanBtn * faceScanBtn;
@property (nonatomic, strong) WXPFaceErrorExampleView * errorExampleView;
@property (nonatomic, strong) WXPLivenessFailView * livenessFailView;

@property (nonatomic, strong) WXPCommonAgreementView * agreementView;

@property (nonatomic, assign) BOOL skipLiven;

@end

@implementation WXPLoginAuthVC

#pragma mark - lazy
- (WXPNavView *)navView{
    if (!_navView) {
        _navView = [WXPNavView new];
        [_navView resetViewWithTitle:@"Verificación Facial"];
        _navView.btnService.blockServiceClick = ^{
            ServiceVC * vc = [ServiceVC new];
            vc.isHideRightNavBtn = true;
            [Global_Nav pushViewController:vc animated:true];
        };
    }
    return _navView;
}
- (WXPTextRemindView *)remindView
{
    if (_remindView == nil) {
        _remindView = [WXPTextRemindView  new];
        [_remindView resetHiddenCloseBtnViewWithContent:@"Para la seguridad de su cuenta, utilice el reconocimiento facial para asegurarse de que es usted quien está utilizando la app."];
    }
    return  _remindView;
}
- (WXPFaceScanBtn *)faceScanBtn
{
    if (_faceScanBtn == nil) {
        _faceScanBtn = [WXPFaceScanBtn new];
        WEAKSELF
        _faceScanBtn.blockAuth = ^{
            [weakSelf requestAuthCheckWithAuthType];
        };
    }
    return  _faceScanBtn;
}
- (WXPFaceErrorExampleView *)errorExampleView{
    if (!_errorExampleView) {
        _errorExampleView = [WXPFaceErrorExampleView new];
    }
    return _errorExampleView;
}
- (WXPCommonAgreementView *)agreementView{
    if (!_agreementView) {
        _agreementView = [WXPCommonAgreementView new];
        _agreementView.centerXBottom = XY(SCREEN_WIDTH/2, SCREEN_HEIGHT-LEFT_MARDIN);
    }
    return _agreementView;
}
- (WXPLivenessFailView *)livenessFailView
{
    if (_livenessFailView == nil) {
        _livenessFailView = [WXPLivenessFailView  new];
    }
    return  _livenessFailView;
}

#pragma mark - viewDidLoad
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_LoginFacial action:KEY_Enter extInfo:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
}

#pragma mark - configUI
- (void)configUI{
    self.view.backgroundColor = COLOR_BACKGROUND;
    self.viewBG.backgroundColor = COLOR_BACKGROUND;
    self.tableView.backgroundColor = COLOR_BACKGROUND;
    [self.view addSubview:self.navView];
    [self.view addSubview:self.agreementView];
    
    self.tableView.height = self.agreementView.top-self.navView.bottom;
    
    [self resetHeaderView];
}

- (void)resetHeaderView{
    self.headerView = [UIView initWithViews:@[
        [GlobalMethod getViewWithHeight:16],
        self.remindView,
        [GlobalMethod getViewWithHeight:27],
        self.faceScanBtn,
        [GlobalMethod getViewWithHeight:45],
        self.errorExampleView,
    ]];
    self.tableView.tableHeaderView = self.headerView;
}

#pragma mark -  跳转去认证
// 活体拍照
- (void)jumpToLiveness{
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_LoginFacial action:KEY_Liveness_Do extInfo:@{@"livenChannel": @"SILENCE_LIVENESS"}];
    //[GlobalMethod userBehaviorTrackWithPageName:KEY_VerifyFacial featureName:KEY_Liveness_Click action:KEY_BUTTON_CLICK type:KEY_button];
    WEAKSELF
    WXPFaceCameraVC * vc = [WXPFaceCameraVC new];
    vc.liveType = 1;
    vc.phone = self.phone;
    vc.livenChannelEnum = KEY_SILENCE_LIVENESS;
    vc.liveTypeEnum = KEY_LOGIN_LIVE;
    vc.blockUploadSuccess = ^(NSString *url, NSString *photoName, NSString *livenessId) {
        [weakSelf requestAuthSuccessLoginWithLiveImg:photoName livenessId:livenessId livenChannelEnum:KEY_SILENCE_LIVENESS];
    };
    vc.blockUploadFail = ^(NSString * errorStr) {
        [weakSelf uploadFailIsH5:false];
    };
    [Global_Nav pushViewController:vc animated:true];
}

// H5活体拍照
- (void)jumpToLivenessH5{
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_LoginFacial action:KEY_Liveness_Do extInfo:@{@"livenChannel": @"CLOUDUN_H5_V3"}];
    WXPWebLivenessVC * vc = [WXPWebLivenessVC new];
    vc.liveTypeEnum = KEY_LOGIN_LIVE;
    vc.phone = self.phone;
    WEAKSELF
    vc.blockUploadSuccess = ^(NSString *url, NSString *photoName, NSString *livenessId) {
        [weakSelf requestAuthSuccessLoginWithLiveImg:photoName livenessId:livenessId livenChannelEnum:KEY_SILENCE_LIVENESS];
    };
    vc.blockUploadFail = ^(NSString * errorStr) {
        // 打点
        [GlobalMethod hitPointWithPageName:KEY_LoginFacial action:KEY_Liveness_Failure extInfo:@{@"errorMsg": errorStr}];
        [weakSelf uploadFailIsH5:true];
    };
    [Global_Nav pushViewController:vc animated:true];
}
- (void)uploadFailIsH5:(BOOL)isH5 {
//    self.errorExampleView.bigImg.hidden = false;
//    self.errorExampleView.livenessImage.hidden = true;
    if (isH5 == false) {
        // h5活体失败。不弹窗
        [self.view addSubview:self.livenessFailView];
    }
}

#pragma mark - request
// 检查用户是否可以做某项授权
- (void)requestAuthCheckWithAuthType{
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_LoginFacial action:KEY_Liveness_Click extInfo:nil];
    WEAKSELF
    [RequestApi requestCheckUserCanAuthWithType:KEY_LIVENESS phone:self.phone delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        if([response boolValueForKey:KEY_checkResult]){
            // true：调用获取活体渠道接口，根据返回的skipLiven执行不同的逻辑
            [GlobalMethod isOpenCamearPermissionsWithCompletion:^(BOOL granted) {
                if(granted){
                    [GlobalMethod mainQueueBlock:^{
                        [weakSelf requestAuthLivenConfig];
                    }];
                }
            }];
        }else{
            // 当接口返回‘false’时，弹窗提示
            [GlobalMethod showAlert:@"Lo sentimos. Aún no es la fecha del evento"];
        }
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

// 获取活体渠道接口
- (void)requestAuthLivenConfig{
    [RequestApi requestNewAuthLivenConfigWithPhone:self.phone delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        // 点击拍照
        self.skipLiven = [response boolValueForKey:KEY_skipLiven];
        // false：根据返回的参数值进行判断
        if (isStr([response stringValueForKey:KEY_SILENCE_LIVENESS])){
            // SILENCE_LIVENESS不为null：跳转静默活体页开始做静默活体拍照
            // 先验证相机，验证成功再去拍照
            [GlobalMethod isOpenCamearPermissionsWithCompletion:^(BOOL granted) {
                if(granted){
                    [GlobalMethod mainQueueBlock:^{
                        [self jumpToLiveness];
                    }];
                }
            }];
        }else if (isStr([response stringValueForKey:KEY_CLOUDUN_H5_V3])){
            // CLOUDUN_H5_V3不为null：跳转LivenessH5 SDK-2活体进行识别
            [self jumpToLivenessH5];
        }
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

// 活体认证之后的登录
- (void)requestAuthSuccessLoginWithLiveImg:(NSString *)liveImg livenessId:(NSString *)livenessId livenChannelEnum:(NSString *)livenChannelEnum{
    // 打点
    // [GlobalMethod userBehaviorRecordWithPageName:@"Register" action:@"Click" extInfo:@{@"vcode": UnPackStr(self.verificacionCode)}];
    // [GlobalMethod userBehaviorTrackWithPageName:KEY_Register featureName:KEY_Register_Login action:KEY_BUTTON_CLICK type:KEY_button];
    [RequestApi requestLiveSuccessLoginWithPhone:[self.phone removeHeadAndTailSpace] vcode:[self.code removeHeadAndTailSpace] liveImg:liveImg livenessId:livenessId livenChannelEnum:livenChannelEnum delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        if (self.blockAddTracking){
            self.blockAddTracking();
        }
        [GlobalMethod hitPointWithPageName:KEY_LoginFacial action:KEY_Liveness_Success extInfo:nil];
        [Global_Nav popToRootViewControllerAnimated:YES];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        [GlobalMethod hitPointWithPageName:KEY_LoginFacial action:KEY_Liveness_Failure extInfo:@{@"errorMsg": errorStr}];
    }];
}



@end
